﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using System.Net;
using System.IO;

namespace Chapter26.BasicWebClient
{
    /// <summary>
    /// AsyncRequestWindow.xaml 的交互逻辑
    /// </summary>
    public partial class AsyncRequestWindow : Window
    {
        public AsyncRequestWindow()
        {
            InitializeComponent();

            var hao360WebRequest = WebRequest.Create("https://hao.360.cn");
            hao360WebRequest.BeginGetResponse(OnResponse, hao360WebRequest);
        }

        protected void OnResponse(IAsyncResult ar)
        {
            var hao360WebRequest = ar.AsyncState as WebRequest;
            var hao360WebResponse = hao360WebRequest.EndGetResponse(ar);
            using (var hao360StreamReader = new StreamReader(hao360WebResponse.GetResponseStream()))
            {
                var line = string.Empty;
                while ((line = hao360StreamReader.ReadLine()) != null)
                {
                    Dispatcher.Invoke(() => responseListBox.Items.Add(line));
                }
            }
        }
    }
}
